<template>
  <TopNav />
  <div class="user-profile-container" :class="theme">
    <div class="profile-header">
      <div class="header-content">
        <div class="avatar-section">
          <img :src="user.avatar || 'https://via.placeholder.com/150'" alt="用户头像" class="avatar" />
          <button class="edit-avatar-btn" @click="editAvatar">
            <i class="fas fa-camera"></i>
          </button>
        </div>
        <div class="user-info">
          <h1>{{ profile.nickname || user.username || '未填写' }}</h1>

          <p class="bio">
            {{ profile.bio || '未填写' }}
          </p>

          <div class="meta-info">
            <span class="meta-item">
              <i class="fas fa-map-marker-alt"></i>
              {{ profile.location || '未填写' }}
            </span>

            <span class="meta-item">
              <i class="fas fa-briefcase"></i>
              {{ profile.profession || '未填写' }}
            </span>

            <span class="meta-item">
              <i class="fas" :class="genderIcon"></i>
              {{ genderText || '未填写' }}
            </span>

            <!-- <span class="meta-item">
              <i class="fas fa-birthday-cake"></i>
              {{ age ? age + '岁' : '未填写' }}
            </span> -->
          </div>
        </div>

        <div class="action-buttons">
          <button class="btn edit-btn" @click="editProfile">
            <i class="fas fa-edit"></i> 编辑资料
          </button>
          <button class="btn theme-toggle" @click="toggleTheme">
            <i class="fas" :class="themeIcon"></i>
          </button>
        </div>
      </div>
    </div>

    <div class="profile-body">
      <div class="profile-card">
        <div class="card-header">
          <h2><i class="fas fa-info-circle"></i> 基本信息</h2>
        </div>
        <div class="card-body">
          <div class="info-row">
            <span class="info-label">用户名</span>
            <span class="info-value">{{ user.username || '未填写' }}</span>
          </div>

          <div class="info-row">
            <span class="info-label">邮箱</span>
            <span class="info-value">{{ user.email || '未填写' }}</span>
          </div>

          <div class="info-row">
            <span class="info-label">手机号</span>
            <span class="info-value">{{ user.phone || '未填写' }}</span>
          </div>

          <div class="info-row">
            <span class="info-label">性别</span>
            <span class="info-value">{{ genderText || '未填写' }}</span>
          </div>

          <div class="info-row">
            <span class="info-label">生日</span>
            <span class="info-value">{{ formattedBirthday || '未填写' }}</span>
          </div>

          <div class="info-row">
            <span class="info-label">所在地</span>
            <span class="info-value">{{ profile.location || '未填写' }}</span>
          </div>

          <div class="info-row">
            <span class="info-label">职业</span>
            <span class="info-value">{{ profile.profession || '未填写' }}</span>
          </div>
        </div>

      </div>

      <div class="profile-card">
        <div class="card-header">
          <h2><i class="fas fa-user-shield"></i> 账户安全</h2>
        </div>
        <div class="card-body">
          <div class="info-row">
            <span class="info-label">账户状态</span>
            <span class="info-value" :class="user.status ? 'text-success' : 'text-danger'">
              {{ user.status ? '正常' : '已禁用' }}
            </span>
          </div>
          <div class="info-row">
            <span class="info-label">注册时间</span>
            <span class="info-value">{{ formatDate(user.created_at) }}</span>
          </div>
          <div class="security-actions">
            <button class="btn btn-sm change-password" @click="changePassword">
              <i class="fas fa-key"></i> 修改密码
            </button>
            <button class="btn btn-sm logout" @click="logout">
              <i class="fas fa-sign-out-alt"></i> 退出登录
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑资料模态框 -->
    <!-- 编辑资料模态框 -->
    <div v-if="showEditModal" class="modal-overlay">
      <div class="modal-content">
        <div class="modal-header">
          <h3>编辑个人资料</h3>
          <button class="close-btn" @click="showEditModal = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveProfile">
            <!-- 用户基础信息 -->
            <div class="form-group">
              <label>用户名</label>
              <div class="readonly-input">{{ editForm.username }}</div>
            </div>


            <div class="form-group">
              <label>邮箱</label>
              <input type="email" v-model="editForm.email" placeholder="输入邮箱" />
            </div>
            <div class="form-group">
              <label>手机号</label>
              <input type="text" v-model="editForm.phone" placeholder="输入手机号" />
            </div>
            <!-- <div class="form-group">
              <label>头像链接</label>
              <input type="text" v-model="editForm.avatar" placeholder="粘贴头像图片地址" />
            </div> -->
            <div class="form-group">
              <label>选择头像</label>
              <div class="avatar-options">
                <img v-for="n in 5" :key="n" :src="`../../../public/avatar/avatar${n}.png`"
                  :class="{ selected: editForm.avatar === `../../../public/avatar/avatar${n}.png` }"
                  @click="editForm.avatar = `../../../public/avatar/avatar${n}.png`" class="avatar-thumbnail" />
              </div>
            </div>


            <!-- 用户简介信息 -->
            <div class="form-group">
              <label>昵称</label>
              <input type="text" v-model="editForm.nickname" placeholder="输入昵称" />
            </div>
            <div class="form-group">
              <label>个人简介</label>
              <textarea v-model="editForm.bio" placeholder="介绍一下你自己..."></textarea>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label>性别</label>
                <select v-model="editForm.gender">
                  <option value="">请选择</option>
                  <option value="male">男</option>
                  <option value="female">女</option>
                  <option value="other">其他</option>
                </select>
              </div>
              <div class="form-group">
                <label>生日</label>
                <input type="date" v-model="editForm.birthday" />
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label>所在地</label>
                <input type="text" v-model="editForm.location" placeholder="例如: 北京" />
              </div>
              <div class="form-group">
                <label>职业</label>
                <input type="text" v-model="editForm.profession" placeholder="例如: 设计师" />
              </div>
            </div>

            <div class="form-actions">
              <button type="button" class="btn btn-cancel" @click="showEditModal = false">取消</button>
              <button type="submit" class="btn btn-save">保存更改</button>
            </div>
          </form>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, computed, inject, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import TopNav from "../../components/TopNav.vue";
import { getUserDetailsByIdApi, updateUserDetailsByIdApi } from '../../api/authService.js';
const userId = localStorage.getItem("userId");
// 主题功能
const theme = inject("theme", ref('light'));
const toggleTheme = () => {
  theme.value = theme.value === 'light' ? 'dark' : 'light';
};

const themeIcon = computed(() => theme.value === 'light' ? 'fa-moon' : 'fa-sun');

const router = useRouter();

// 模拟用户数据 - 实际应用中应该从API获取
const user = ref({
  id: 1,
  username: 'example_user',
  email: 'user@example.com',
  phone: '13800138000',
  avatar: '../../../public/avatar/default-avatar.png',
  status: 1,
  created_at: '2023-01-15T08:30:00Z'
});

const profile = ref({
  nickname: '小明',
  bio: '热爱编程和设计的全栈开发者，喜欢分享知识和经验。',
  gender: 'male',
  birthday: '1990-05-20',
  location: '北京',
  profession: '前端工程师'
});

// 计算属性
const genderText = computed(() => {
  const map = { male: '男', female: '女', other: '其他' };
  return profile.value.gender ? map[profile.value.gender] : '';
});

const genderIcon = computed(() => {
  const map = { male: 'fa-male', female: 'fa-female', other: 'fa-genderless' };
  return profile.value.gender ? map[profile.value.gender] : '';
});

const formattedBirthday = computed(() => {
  if (!profile.value.birthday) return '';
  const date = new Date(profile.value.birthday);
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
});

const age = computed(() => {
  if (!profile.value.birthday) return '';
  const birthDate = new Date(profile.value.birthday);
  const today = new Date();
  let age = today.getFullYear() - birthDate.getFullYear();
  const m = today.getMonth() - birthDate.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  return age;
});

// 编辑功能
const showEditModal = ref(false);
const editForm = ref({});

const editProfile = () => {
  editForm.value = {
    // 来自 users 表
    username: user.value.username || '',
    email: user.value.email || '',
    phone: user.value.phone || '',
    avatar: user.value.avatar || '',

    // 来自 user_profiles 表
    nickname: profile.value.nickname || '',
    bio: profile.value.bio || '',
    gender: profile.value.gender || '',
    birthday: profile.value.birthday || '',
    location: profile.value.location || '',
    profession: profile.value.profession || ''
  };
  showEditModal.value = true;
};


function getVisualLength(str) {
  let len = 0;
  for (let char of str) {
    len += /[\u4e00-\u9fa5]/.test(char) ? 1 : 0.2; // 中文 1，英文 0.5
  }
  return len;
}


const saveProfile = () => {
  // 校验规则
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  const phoneRegex = /^1[3-9]\d{9}$/;

  // 校验逻辑
  if (!editForm.value.email || !emailRegex.test(editForm.value.email)) {
    return alert('请输入有效的邮箱');
  }

  if (editForm.value.phone && !phoneRegex.test(editForm.value.phone)) {
    return alert('请输入正确的手机号');
  }

  if (editForm.value.nickname && editForm.value.nickname.length > 20) {
    return alert('昵称不能超过 20 个字符');
  }

  const visualLen = getVisualLength(editForm.value.bio);
  if (visualLen > 20) {
    return alert('个人简介不能超过 20 个字符（中文 20，英文最多约 100 个字母）');
  }

  if (!editForm.value.gender && !['male', 'female', 'other'].includes(editForm.value.gender)) {
    return alert('请选择合法的性别');
  }

  // 如果都通过，合并数据并提交
  profile.value = { ...profile.value, ...editForm.value };

  const handAfterEditProfile = {
    username: profile.value.username,
    email: profile.value.email,
    phone: profile.value.phone,
    avatar: profile.value.avatar.match(/avatar\d+/)?.[0] || 'avatar1',
    nickname: profile.value.nickname,
    bio: profile.value.bio,
    gender: profile.value.gender,
    birthday: new Date(profile.value.birthday).toLocaleDateString('en-CA'),
    location: profile.value.location,
    profession: profile.value.profession
  };

  updateUserDetailsById(handAfterEditProfile);
  showEditModal.value = false;
};


const updateUserDetailsById = async (sendData) => {
  try {
    const response = await updateUserDetailsByIdApi(userId, sendData);
    if (response) {
      console.log(response);
      // 跟新成功后重新加载页面数据
      loadPageData()
    } else {
      console.log('更新失败');
    }
  } catch (error) {
    console.log('更新失败', error);
  }
}

// 其他功能
const editAvatar = () => {
  alert('头像编辑功能待实现');
};

const changePassword = () => {
  router.push('/Changepassword');
};

const logout = () => {
  // 登出逻辑
  router.push('/login');
};

const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};



const getUserDetailsById = async (userId) => {
  try {
    const response = await getUserDetailsByIdApi(userId)
    // console.log(response);
    if (response) {
      return response.user;
      // console.log(response);
    } else {
      console.log('获取用户信息失败');
    }
  } catch (error) {
    console.log('获取用户信息失败', error);
  }
}


const loadPageData = async () => {
  try {
    const [UserDetailsData] = await Promise.all([
      getUserDetailsById(userId)
    ])

    console.log(UserDetailsData);
    user.value = {
      id: UserDetailsData.user_id,
      username: UserDetailsData.username,
      email: UserDetailsData.email,
      phone: UserDetailsData.phone,
      avatar: `../../../public/avatar/${UserDetailsData.avatar}.png`,
      status: 1,
      created_at: UserDetailsData.user_created_at,
    }
    profile.value = {
      nickname: UserDetailsData.nickname,
      bio: UserDetailsData.bio,
      gender: UserDetailsData.gender,
      birthday: UserDetailsData.birthday,
      location: UserDetailsData.location,
      profession: UserDetailsData.profession,
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('请求数据失败')
  }
}


// 模拟获取数据
onMounted(() => {
  // 实际应用中这里应该是API调用
  // getUserDetailsById(userId)
  loadPageData()
  console.log('加载用户数据');
});
</script>

<style scoped>
.user-profile-container {
  --bg-color: #f8f9fa;
  --text-color: #333;
  --primary-color: #4361ee;
  --secondary-color: #6c757d;
  --border-color: #e1e4e8;
  --card-bg: #fff;
  --hover-bg: #f1f3f5;
  --shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  --success-color: #28a745;
  --danger-color: #dc3545;
  --warning-color: #ffc107;
  min-height: 100vh;
  background-color: var(--bg-color);
  color: var(--text-color);
  transition: all 0.3s ease;
}

.user-profile-container.dark {
  --bg-color: #1a1a1a;
  --text-color: #e0e0e0;
  --primary-color: #4895ef;
  --secondary-color: #8e8e8e;
  --border-color: #333;
  --card-bg: #2d2d2d;
  --hover-bg: #383838;
  --shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.profile-header {

  /* background-color: var(--card-bg); */
  /* border: ; */
  /* color: white; */
  padding: 2rem 0;
  margin-bottom: 2rem;
  /* box-shadow: var(--shadow); */
}

.header-content {
  /* background-color: var(--card-bg); */
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1rem;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 2rem;
  color: var(--text-color);
}

.avatar-section {
  position: relative;
  width: 120px;
  height: 120px;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid rgba(255, 255, 255, 0.3);
}

.edit-avatar-btn {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: var(--primary-color);
  color: white;
  border: 2px solid white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
}

.edit-avatar-btn:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.user-info {
  flex: 1;
  min-width: 300px;
}

.user-info h1 {
  margin: 0;
  font-size: 2rem;
  font-weight: 600;
}

.bio {
  margin: 0.5rem 0;
  opacity: 0.9;
  line-height: 1.5;
}

.meta-info {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  margin-top: 0.5rem;
  font-size: 0.9rem;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 0.3rem;
}

.action-buttons {
  display: flex;
  gap: 1rem;
  align-items: flex-start;
}

.btn {
  padding: 0.5rem 1rem;
  border-radius: 6px;
  border: none;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.edit-btn {
  background-color: var(--border-color);
  color: var(--primary-color);
}

.edit-btn:hover {
  background-color: rgba(145, 145, 145, 0.9);
}

.theme-toggle {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: var(--border-color);
  color: var(--text-color);
  justify-content: center;
}

.theme-toggle:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.profile-body {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1rem 2rem;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 1.5rem;
}

.profile-card {
  background-color: var(--card-bg);
  border-radius: 10px;
  box-shadow: var(--shadow);
  overflow: hidden;
}

.card-header {
  padding: 1rem 1.5rem;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.card-header h2 {
  margin: 0;
  font-size: 1.2rem;
  font-weight: 600;
}

.card-body {
  padding: 1.5rem;
}

.info-row {
  display: flex;
  margin-bottom: 1rem;
  padding-bottom: 1rem;
  border-bottom: 1px dashed var(--border-color);
}

.info-row:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.info-label {
  width: 100px;
  font-weight: 500;
  color: var(--secondary-color);
}

.info-value {
  flex: 1;
}

.text-success {
  color: var(--success-color);
}

.text-danger {
  color: var(--danger-color);
}

.security-actions {
  display: flex;
  gap: 1rem;
  margin-top: 1.5rem;
}

.btn-sm {
  padding: 0.4rem 0.8rem;
  font-size: 0.9rem;
}

.change-password {
  background-color: var(--primary-color);
  color: white;
}

.change-password:hover {
  background-color: #3a56d8;
}

.logout {
  background-color: var(--danger-color);
  color: white;
}

.logout:hover {
  background-color: #c82333;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: var(--card-bg);
  border-radius: 10px;
  width: 100%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.modal-header {
  padding: 1.5rem;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 1.3rem;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: var(--secondary-color);
  padding: 0.5rem;
}

.close-btn:hover {
  color: var(--text-color);
}

.modal-body {
  padding: 1.5rem;
}

.form-group {
  margin-bottom: 1.2rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 0.6rem 0.8rem;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  background-color: var(--card-bg);
  color: var(--text-color);
  font-size: 1rem;
}

.form-group textarea {
  min-height: 100px;
  resize: vertical;
}

.form-row {
  display: flex;
  gap: 1.5rem;
}

.form-row .form-group {
  flex: 1;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1.5rem;
}

.btn-cancel {
  background-color: var(--secondary-color);
  color: white;
}

.btn-cancel:hover {
  background-color: #5a6268;
}

.btn-save {
  background-color: var(--primary-color);
  color: white;
}

.btn-save:hover {
  background-color: #3a56d8;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    text-align: center;
  }

  .action-buttons {
    width: 100%;
    justify-content: center;
  }

  .user-info {
    text-align: center;
  }

  .meta-info {
    justify-content: center;
  }

  .form-row {
    flex-direction: column;
    gap: 0;
  }

  .profile-body {
    grid-template-columns: 1fr;
  }
}

.avatar-options {
  display: flex;
  gap: 10px;
}

.avatar-thumbnail {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  cursor: pointer;
  border: 2px solid transparent;
  transition: border 0.2s ease;
}

.avatar-thumbnail.selected {
  border-color: #007bff;
}

.readonly-input {
  padding: 6px 12px;
  border: 1px solid var(--border-color);
  background-color: var(--card-bg);
  color: #666;
  border-radius: 4px;
}
</style>